
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    InitUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitUI()
{
    this->resize((CHESS_C+1)*MAX_X,(CHESS_R+1)*MAX_Y);
    this->setMaximumSize((CHESS_C+1)*MAX_X,(CHESS_R+1)*MAX_Y);//固定最大
    this->setMinimumSize((CHESS_C+1)*MAX_X,(CHESS_R+1)*MAX_Y);//固定最小
    this->setWindowTitle("五子棋的乐趣");//窗口名称
    //棋盘大小制作

    b_black=false;

}

void MainWindow::DrawChessBoard()
{
    QPainter painter(this);//绘图
    painter.setPen(QPen(QColor(Qt::black),2));//边框的颜色大小
    painter.setBrush(Qt::gray);//棋盘颜色
    for(int i=0;i<CHESS_C;i++)//二重循环绘制所有格子
    {
        for(int j=0;j<CHESS_R;j++)
        {
            painter.drawRect((i+0.5)*MAX_X,(j+0.5)*MAX_Y,MAX_X,MAX_Y);//造矩形格子

        }
    }

}

void MainWindow::paintEvent(QPaintEvent *event)
{
    DrawChessBoard();
    DrawMouseChess();
    DrawChessItem();


    update();//强制更新

}
void  MainWindow::DrawMouseChess()
{
    QPainter painter(this);
    painter.setPen(QPen(QColor(Qt::transparent)));//棋子的边框透明
    if(b_black)
    {
        painter.setBrush(Qt::black);

    }
    else
    {
        painter.setBrush(Qt::white);

    }
    painter.drawEllipse(mapFromGlobal(QCursor::pos()),MAX_X/2,MAX_Y/2);
    //获取鼠标位置，圆半径

}
void  MainWindow::DrawChessItem()
{
    QPainter painter(this);
    painter.setPen(QPen(QColor(Qt::transparent)));//棋子的边框透明
    //painter.setBrush(Qt::black);
    //painter.drawEllipse(65,65,50,50);
    for(int i=0;i<p_ChessItem.size();i++)//棋子开始绘制
    {
        ChessItem item = p_ChessItem[i];//当前棋子位置赋值给棋子类
        if(item._black)
        {
            painter.setBrush(Qt::black);
        }
        else
        {
            painter.setBrush(Qt::white);
        }
        DrawChessAtpoint(painter,item._pt);
    }
}
void MainWindow::DrawChessAtpoint(QPainter&painter,QPoint&point)
{
    QPoint ptCenter((point.x()+0.5)*MAX_X,(point.y()+0.5)*MAX_Y);//获取棋子摆放位置
    painter.drawEllipse(ptCenter,MAX_X/2,MAX_Y/2);

}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<event->pos()<<Qt::endl;//鼠标点击位置

    QPoint pt;//点位
    pt.setX((event->pos().x())/MAX_X);
    pt.setY((event->pos().y())/MAX_Y);

    //判断棋子存在性
    for(int i=0;i<p_ChessItem.size();i++)
    {
        ChessItem item = p_ChessItem[i];
        if(item._pt==pt)
        {
            return;//存在不处理
        }
    }

    //不存在就要绘制并且判断五子连接性
    ChessItem item(pt,b_black);
    p_ChessItem.append(item);


}
int MainWindow::CountNearItem(ChessItem item,QPoint pt)
{
    int nCount=0;

    item._pt +=pt;
    while(p_ChessItem.contains(item))
    {
        nCount++;
        item._pt +=pt;

    }

    return nCount;

}

